<!--
* description: 展车订单配车
* author: wangjuan
* createdDate: 2020-11-13
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-table-cols="tableCols"
      :dynamic-api-config="apiConfig"
      :dynamic-form-fields="formField"
      :dynamic-is-show-select="true"
      :dynamic-is-show-more-btn="false"
      :callback-obj="callbackObj"
    />

    <manualSCar
      :key="manualSCarPopupsKey"
      :popups-visible="manualSCarPopupsVisible"
      :manual-row-data="manualSCarRowData"
      :popups-state="manualSCarPopupsState"
      @closemanualSCar="closemanualSCar"
    />

    <batchSupplyCar
      :key="batchSupplyCarPopupsKey"
      :popups-visible="batchSupplyCarPopupsVisible"
      :batch-row-data="batchSupplyCarRowData"
      :popups-state="batchSupplyCarPopupsState"
      @closebatchSupplyCar="closebatchSupplyCar"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible="editPopupsVisible"
      :popups-state="editPopupsState"
      @closeEdit="closeEdit"
      @close="closeEdit"
    />

  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import manualSCar from './manualSCar'
import batchSupplyCar from './batchSupplyCar'
import api from '@/api/belowInfo'
export default {
  name: 'BelowOrdCar',
  components: {
    OneTableTemplate,
    Edit: () => import('./edit'),
    manualSCar,
    batchSupplyCar
  },

  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      manualSCarPopupsKey: 'manualSCar',
      manualSCarPopupsState: '',
      manualSCarRowData: {},
      manualSCarPopupsVisible: false,
      editPopupsVisible: false,
      batchSupplyCarPopupsKey: 'batchSupplyCar',
      batchSupplyCarPopupsState: '',
      batchSupplyCarRowData: {},
      batchSupplyCarPopupsVisible: false,
      editRowData: {},
      // 网格查询API配置对象
      apiConfig: api.queryExhibitionCarOrderInfo,
      list: [],
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          // clickEvent: this.solutionWith,
          clickEvent: () => this.showCol(),
          text: '解配',
          position: 'left',
          disabled: true
        },
        {
          compKey: 'btnKey6',
          size: 'small',
          name: 'export',
          clickEvent: () => this.export(),
          text: '导出',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              labelName: '批次编号：',
              codeField: 'transferOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '订单编号：',
              codeField: 'saleOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '交付门店：',
              codeField: 'deliveryDlrId',
              oFields: 'deliveryDlrId,deliveryDlrShortName',
              customObj: {
                api: api.ListOfDeliveryStoreContent
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '创建时间：',
              codeField: 'startDate,endDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              dateType: 'daterange',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '负责人姓名：',
              codeField: 'chargeMen',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey6',
              labelName: '负责人电话：',
              codeField: 'chargePhone',
              validrule: { isPhone: true, noRequire: false, maxlength: 11 },
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey7',
              labelName: '订单状态：',
              codeField: 'orderStatus',
              lookuptype: 'VE1003',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey8',
              labelName: '展车门店：',
              codeField: 'dlrId',
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMust: false,
              oFields: 'dlrId,dlrShortName',
              customObj: {
                api: api.listOfStore
              }
              // codeField: 'dlrFullName',
              // component: () => import('@/components/org/commonInput'),
              // type: 'inputText',
            },
            {
              compKey: 'compKey9',
              labelName: '车系：',
              codeField: 'carSeriesId',
              oFields: 'carSeriesId,carSeriesCn',
              customObj: {
                api: { APIUrl: api.listOfCarSeries.APIUrl }
              },
              component: () => import('@/components/org/commonSelect'),
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey10',
              labelName: '基础车型：',
              codeField: 'carConfigId',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carConfigId,carConfigCn',
              parentFileds: 'value:carSeriesId',
              customObj: {
                listQuery: {
                  carSeriesId: ''
                },
                api: { APIUrl: api.queryCarType.APIUrl }
              },
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey11',
              labelName: '选装包：',
              codeField: 'optionalPagId',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'optionalPagId,optionalPagName',
              parentFileds: 'value:carConfigId|carSeriesId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: ''
                },
                api: { APIUrl: api.queryCarOptionalPagLinkMessage.APIUrl }
              },
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey12',
              labelName: '车身颜色：',
              codeField: 'carColorId',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carColorId,carColorName',
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: { APIUrl: api.queryCarColorLinkMessage.APIUrl }
              },
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey13',
              labelName: '内饰颜色：',
              codeField: 'carIncolorId',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'carIncolorId,carIncolorName',
              parentFileds: 'value:carConfigId|carSeriesId|optionalPagId',
              customObj: {
                listQuery: {
                  carConfigId: '', carSeriesId: '', optionalPagId: ''
                },
                api: { APIUrl: api.queryCarInColorLinkMessage.APIUrl }
              },
              type: 'dropdownList',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey14',
              labelName: 'VIN：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            },
            {
              compKey: 'compKey15',
              labelName: '销售计划号：',
              codeField: 'salePlanCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'saleOrderId',
              label: '主键ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'controlBtn',
              label: '操作',
              minWidth: 180,
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey1',
                  labelName: '配车',
                  rowFileds: 'show:orderStatus-合同已签署',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.manualSCar(index)
                },
                {
                  compKey: 'propKey2',
                  labelName: '编辑',
                  rowFileds: 'show:orderStatus-合同已签署',
                  component: () => import('@/components/org/linkButton'),
                  clickEvent: (index) => this.edit(index)
                }
              ]
            },
            {
              prop: 'transferOrderCode',
              label: '批次编号',
              width: 140
            },
            {
              prop: 'saleOrderCode',
              label: '订单编号',
              width: 140
            },
            {
              prop: 'orderStatus',
              label: '订单状态'
            },
            {
              prop: 'carSeriesCn',
              label: '车系'
            },
            {
              prop: 'carConfigCn',
              label: '基础车型'
            },
            {
              prop: 'optionalPagName',
              label: '选装包'
            },
            {
              prop: 'carColorName',
              label: '车身颜色'
            },
            {
              prop: 'carIncolorName',
              label: '内饰颜色'
            },
            {
              prop: 'vin',
              label: 'VIN码',
              width: 140
            },
            {
              prop: 'salePlanCode',
              label: '销售计划号',
              width: 140
            },
            {
              prop: 'dlrType',
              label: '门店大类'
            },
            {
              prop: 'deliveryDlrShortName',
              label: '交付门店',
              width: 140
            },
            {
              prop: 'dlrShortName',
              label: '展车门店',
              width: 140
            },
            {
              prop: 'chargeMen',
              label: '负责人姓名'
            },
            {
              prop: 'chargePhone',
              label: '负责人电话',
              width: 140
            },
            {
              prop: 'creator',
              label: '创建人'
            },
            {
              prop: 'createdDate',
              label: '创建时间',
              width: 140
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ],

      formField: this.$utils.getFormField(this, {
        transferOrderCode: '',
        saleOrderCode: '',
        deliveryDlrShortName: '',
        deliveryDlrId: '',
        startDate: '',
        endDate: '',
        chargeMen: '',
        chargePhone: '',
        orderStatus: '',
        dlrFullName: '',
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        carColorId: '',
        carIncolorId: '',
        salePlanCode: '',
        dlrId: '',
        vin: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      // 单表格模版页面组件回调事件
      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          const getValArray = (array) => (attr) => array.map(item => item[attr])
          this.list = getValArray(selection)
          this.handleSelectionChange(selection)
        }
      }
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    // 选择列是否生效
    getSelectable(row, index) {
      if (row.orderStatus === '订单已配车') {
        return true
      }
    },
    // 解配
    showCol() {
      this.$requestAPI({
        apiUrl: api.updateRelieveCar.APIUrl,
        variables: {
          SALE_ORDER_D_ID: this.list('SALE_ORDER_D_ID'),
          carId: this.list('carId'),
          saleOrderId: this.list('saleOrderId'),
          updateControlId: this.list('updateControlId'),
          vin: this.list('vin'),
          salePlanCode: this.list('salePlanCode'),
          isVip: this.list('isVip'),
          dlrCode: this.list('dlrCode'),
          updateControlIdD: this.list('updateControlIdD')
        }
      }).then(res => {
        this.queryTable(1)
      })
    },
    // 关闭
    shut() {
      this.$requestAPI({
        apiUrl: api.closeExhibitionCarOrder.APIUrl,
        variables: { saleOrderId: this.list('saleOrderId'), updateControlId: this.list('updateControlId') }
      }).then(res => {
        this.queryTable(1)
      })
    },
    // 导出
    export() {
      const loading = this.$loading({
        text: '正在导出...'
      })
      var date = new Date()
      var year = date.getFullYear()
      var month = date.getMonth() + 1
      var day = date.getDate()
      month = (month < 10 ? '0' + month : month)
      day = (day < 10 ? '0' + day : day)
      var mydate = year.toString() + month.toString() + day.toString()
      const returnObj = {
        // api配置
        apiConfig: api.exportExhibitionCarOrderManage,
        variables: { ...this.formField, saleOrderId: this.list.length > 0 ? this.list('saleOrderId') : [] }
      }
      returnObj.variables.dataType = 'excel'
      const paramD = this.$getParams(returnObj)
      this.$requestAPI(paramD).then(res => {
        loading.close()
        this.$utils.downloadFile(res, `展车订单配车${mydate}.xlsx`)
      })
    },

    // 打开手动配车弹窗
    manualSCar(index) {
      this.manualSCarPopupsVisible = true
      this.manualSCarPopupsKey = this.$utils.generateId()
      this.manualSCarRowData = this.$refs.multipleTable.list[index]
    },

    // 关闭手动配车弹窗
    closemanualSCar() {
      this.queryTable(1)
      this.manualSCarPopupsVisible = false
      this.manualSCarPopupsKey = this.$utils.generateId()
    },

    // 打开批量配车弹窗
    batchSupplyCar(index) {
      this.batchSupplyCarPopupsVisible = true
      this.batchSupplyCarPopupsKey = this.$utils.generateId()
    },

    // 关闭批量配车弹窗
    closebatchSupplyCar() {
      this.batchSupplyCarPopupsVisible = false
      this.batchSupplyCarPopupsKey = this.$utils.generateId()
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },
    // 关闭编辑弹窗
    closeEdit() {
      this.editPopupsVisible = false
      this.queryTable(1)
    },
    // 编辑
    edit(index) {
      this.editRowData = this.$refs['multipleTable'].list[index]
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
    }
    // hiddenColData(data) {
    //   if (data && data.length > 0) {
    //     this.refreshTableKey += 1
    //     this.dynamicTableCols = data
    //   }
    // },
  }
}
</script>
